

import "./index.scss"
import { Row, Col, Typography, Tabs, Form, Input, Button, Checkbox, message } from "antd"
import { useRef, useEffect, useState } from "react"
import { UserOutlined, LockOutlined, PhoneOutlined, AppstoreOutlined } from '@ant-design/icons';
import { reg } from "../../utils/validate"
import { withRouter } from "react-router-dom"
import { HashHistroy } from "../../utils";
import { $http } from "../../api";
import { mbdata } from "../../mobx/data";
const { Title } = Typography;
const { TabPane } = Tabs;
const { pwd, account, phone } = reg;
export default function Login({ history, location }) {


    return (
        <div className="login">
            <video
                className="myvideo"
                id="myvideo"
                autoPlay
                loop
                playsInline
                muted
                src="https://www.mercedes-benz.com.cn/content/dam/mb-cn/dealers/wwhm30/%E6%96%87%E4%BB%B6%E5%A4%B9/AMG_GT_ALL_1_original.mp4"
            // src="https://www.mercedes-benz.com.cn/content/dam/mb-cn/renovation/renovation-homepage/0122update-cs-video/service.mp4"
            ></video>
            <Row className="mybox  ">
                <Col className="login-box" xs={22} sm={18} md={14} lg={12} xl={6} xxl={4}>
                    <Title className="title" level={3}>
                        {/* 梅赛德斯奔驰后台管理系统 */}
                        <img style={{
                            width: 180,
                            height: 32,
                            margin: "0 auto"
                        }} src="" alt="" />
                    </Title>


                    <Tabs defaultActiveKey="1" >
                        <TabPane tab="密码登录" key="1">
                            <LoginByPass history={history} location={location}></LoginByPass>
                        </TabPane>
                        <TabPane tab="手机登录" key="2">
                            <LoginByCodeRoute ></LoginByCodeRoute>
                        </TabPane>
                    </Tabs>
                </Col>
            </Row>
        </div>
    )
}


const layout = {
    labelCol: {
        span: 6,
        offset: 1
    },
    wrapperCol: {
        span: 16
    }
}

const tailLayout = {
    wrapperCol: {
        span: 16,
        offset: 7
    }
}

// 密码登录
function LoginByPass({ history, location }) {
    useEffect(() => {
        var zhuAccount = new URLSearchParams(location.search).get("account")
        if (zhuAccount) {
            // 注册成功账号
            form.current.setFieldsValue({
                account: zhuAccount,
                password: ""
            })
        } else {
            form.current.setFieldsValue({
                account: localStorage.getItem("account"),
                password: localStorage.getItem("password"),

            })
        }
    }, [])
    const onFinish = value => {
        console.log(value)
        // ajax
        $http.login(value)
            .then(res => {
                if (res.code == 200) {
                    sessionStorage.setItem("token", res.token)
                    if (value.remember) {
                        localStorage.setItem("account", value.account)
                        localStorage.setItem("password", value.password)
                    }
                    mbdata.changeUserInfo(res.result)  //保存用户信息
                    history.push("/main")
                }
            })
    }
    const onFailed = err => {
        console.log(err)
        message.error('请先输入有效的登录信息');
    }
    const gotowhere = url => {
        history.push(url)
    }
    const form = useRef()
    return (
        <div>
            <Form
                name="normal_login"
                className="login-form"
                initialValues={{    // 设置表单的初始值
                }}
                onFinish={onFinish}
                onFinishFailed={onFailed}
                ref={form}
                {...layout}
            >
                <Form.Item
                    name="account"
                    label="用户名"
                    rules={[
                        {
                            required: true,
                            message: '请输入用户名',
                        },
                        // {
                        //     pattern:account,
                        //     message:"账号由字母数字混合"
                        // }
                    ]}
                >
                    <Input prefix={<UserOutlined className="site-form-item-icon" />} placeholder="请输入用户名" />
                </Form.Item>
                <Form.Item
                    name="password"
                    label="密&emsp;码"
                    rules={[
                        {
                            required: true,
                            message: '请输入登录密码',
                        },
                        {
                            pattern: pwd,
                            message: '请输入6-16位数字加字母的登录密码',
                        },
                    ]}
                >
                    <Input.Password prefix={<LockOutlined className="site-form-item-icon" />} placeholder="请输入登录密码" />
                </Form.Item>
                <Form.Item
                    {...tailLayout}
                    name="remember"
                    valuePropName="checked"
                >
                    <Checkbox>记住密码</Checkbox>
                </Form.Item>
                <Form.Item
                    {...tailLayout}
                >
                    <Button block type="primary" htmlType="submit" >登录</Button>
                </Form.Item>
                <Form.Item
                    {...tailLayout}
                    className="links"
                >
                    <span onClick={() => gotowhere("/register")} style={{ color: "#f50" }}>立即注册</span>
                    <span onClick={() => gotowhere("/forgetpass")} style={{ color: "#0f0" }}>忘记密码</span>
                </Form.Item>
            </Form>
        </div>
    )
}

// 手机登录
let captchatime = 10
let timer = null
function LoginByPhone({ history }) {
    const [flag, setFlag] = useState(true)
    const [phonedis, setPhonedis] = useState(false)
    let [count, setCount] = useState(captchatime)
    const onFinish = (value) => {
        $http.checkcaptcha(value)
            .then(res => {
                if (res.code == 200) {
                    sessionStorage.setItem("token", res.token)
                    localStorage.setItem("phone", value.phone)
                    mbdata.changeUserInfo(res.result)  //保存用户信息
                    history.push("/main")
                }
            })
    }
    const onFailed = value => {
        message.error("请先输入有效的登录信息")
    }
    const gotowhere = url => {
        history.push(url)
        // HashHistroy.push(url)
    }


    useEffect(() => {
        if (localStorage.getItem('phone')) {
            setPhonedis(phone.test(localStorage.getItem('phone')))
        }
        return () => {
            // 离开组件
            clearInterval(timer)
            timer = null;
            setFlag(true)
            setCount(captchatime)
        }
    }, [])


    function initTime() {
        timer = setInterval(() => {
            if (count > 0) {
                setCount(--count)
                setFlag(false)
            } else {
                setFlag(true)
                setCount(captchatime)
                clearInterval(timer)
                timer = null
            }
        }, 1000)
    }
    const getCaptcha = () => {
        // 点击发送验证码
        var phonevalue = form.current.getFieldValue("phone")
        setCount(--count)
        setFlag(false)
        initTime()
        // 后台发送
        $http.sendcaptcha({
            phone: phonevalue
        })
            .then(res => {
                if (res.code == 200) {
                }
            })
    }
    const form = useRef()
    const thisphone = useRef()
    const changeCheckPhone = () => {
        var value = form.current.getFieldValue("phone")
        if (phone.test(value)) {
            setPhonedis(true)
        } else {
            setPhonedis(false)
        }
    }
    return (
        <div>
            <Form
                name="normal_login"
                className="login-form"
                initialValues={{    // 设置表单的初始值
                    phone: localStorage.getItem('phone')
                }}
                onFinish={onFinish}
                onFinishFailed={onFailed}
                ref={form}
                {...layout}
            >
                <Form.Item
                    name="phone"
                    label="手机号"
                    rules={[
                        {
                            required: true,
                            message: '请输入手机号',
                        },
                        {
                            pattern: phone,
                            message: "请输入正确的手机号码"
                        }
                    ]}
                >
                    <Input ref={thisphone} onChange={changeCheckPhone} prefix={<PhoneOutlined className="site-form-item-icon" />} placeholder="请输入手机号" />
                </Form.Item>
                <Form.Item
                    name="captcha"
                    label="验证码"
                    rules={[
                        {
                            required: true,
                            message: '请输入验证码',
                        },
                        {
                            pattern: /^\d{4}$/,
                            message: "请输入4位的验证码"
                        }
                    ]}
                >
                    <Row>
                        <Col span={12}>

                            <Input prefix={<AppstoreOutlined className="site-form-item-icon" />} placeholder="请输入验证码" />
                        </Col>
                        <Col span={11} offset={1}>
                            {/* 防抖  避免频繁点击发送 */}
                            {
                                flag ? <Button disabled={!phonedis} type="danger" onClick={getCaptcha} >获取验证码</Button>
                                    :
                                    <Button type="" disabled  >剩余 {count} S</Button>
                            }
                        </Col>
                    </Row>
                </Form.Item>
                <Form.Item {...tailLayout}>
                    <Button type="danger" block htmlType="submit" >立即登录</Button>
                </Form.Item>
                <Form.Item
                    {...tailLayout}
                    className="links"
                >
                    <span onClick={() => gotowhere("/register")} style={{ color: "#f50" }}>立即注册</span>
                    <span onClick={() => gotowhere("/forgetpass")} style={{ color: "#0f0" }}>
                        忘记密码
                    </span>
                </Form.Item>
            </Form>
        </div>
    )
}


const LoginByCodeRoute = withRouter(LoginByPhone)